package com.qingcloud.base.pojo;

import cn.hutool.core.util.StrUtil;
import com.qingcloud.base.exception.WamingException;
import com.qingcloud.base.exception.WamingExceptionEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;

/**
 * API返回结果
 */

@Getter
@Setter
@NoArgsConstructor
public class ApiResult implements Serializable {

    public static ApiResult success(Object object) {
        return new ApiResult(SUCCEED_CODE, "", object, "");
    }
    public static ApiResult success() {
        return new ApiResult(SUCCEED_CODE, "", null, "");
    }

    public static ApiResult fail(String message) {
        return new ApiResult(FAIL_CODE, message, "", "");
    }

    public static ApiResult fail(String message, String trace) {
        return new ApiResult(FAIL_CODE, message, "", trace);
    }

    public static ApiResult fail(int code, String message, String trace) {
        return new ApiResult(code, message, "", trace);
    }

    public static ApiResult fail(int code) {
        return new ApiResult(code, "", "", "");
    }

    public static ApiResult fail(int code,String message) {
        return new ApiResult(code, message, "", "");
    }

    public ApiResult(Integer errorCode, String errorMessage, Object result, String trace) {
        this.code = errorCode;
        this.error = errorMessage;
        this.result = result;
        this.trace = trace;
    }

    public static final Integer SUCCEED_CODE = 0;

    public static final Integer FAIL_CODE = 505;

    @ApiModelProperty(value = "返回码 0成功 其他错误", example = "0")
    protected int code;

    @ApiModelProperty(value = "错误信息，成功时为空", example = "网络错误")
    protected String error;

    @ApiModelProperty(value = "抛出异常时的堆栈信息", example = "throw Exception")
    protected String trace;

    @ApiModelProperty(value = "AJAX结果数据", example = "网络错误")
    private Object result;

    @ApiModelProperty(value = "结果是否成功")
    private boolean successful;

    /**
     * 检查api结果是否成功
     */
    public boolean isSuccessful() {
        return SUCCEED_CODE.equals(this.code);
    }

    /**
     * 检查ApiResult结果是否成功
     */
    public static void checkResult(ApiResult apiResult) {
        if(apiResult==null){
            throw new WamingException(WamingExceptionEnum.REMOTE_ERROR);
        }
        if(!SUCCEED_CODE.equals(apiResult.getCode())){
            String errorMessage = WamingExceptionEnum.REMOTE_ERROR.getMessage();
            String error = apiResult.getError();
            if(StrUtil.isNotBlank(error)){
                errorMessage ="报错信息:"+ error;
            }
            throw new WamingException(WamingExceptionEnum.REMOTE_ERROR.getCode(), errorMessage);
        }
    }
}
